const qs = require("querystring");
const pathToRegexp = require("path-to-regexp");

module.exports = () => {
  return async (ctx, next) => {
    // 兼容
    const { path, url, query } = ctx;
    const keys = [];
    const regExp = pathToRegexp("/appid/:appid/appkey/:appkey/:path*", keys);
    const regRes = regExp.exec(path);
    if (regRes) {
      const appid = regRes[1];
      const appkey = regRes[2];
      const _path = `/${regRes[3]}`;
      const _query = qs.stringify(
        Object.assign(query, {
          "x-qingful-appid": appid,
          "x-qingful-appkey": appkey
        })
      );
      const _url = `${_path}?${_query}`;

      /**
       * koa-router, koa-logger根据originalUrl处理
       */
      Object.assign(ctx, {
        path: _path,
        url: _url,
        originalUrl: _url
      });
    }

    await next();
  };
};
